package com.rxyb.security.config;

import com.rxyb.security.filter.LoginExptionHandler;
import com.rxyb.security.filter.LoginFailHandler;
import com.rxyb.security.filter.LoginSuccessHandler;
import com.rxyb.security.handler.AuthLimitHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author YJH
 * @version 1.0
 * @description Web 认证的怕配置
 * @date 2020/5/15  15:51
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 开启跨越共享
        http.csrf().and().cors().disable();
        // 开启授权认证
        http.authorizeRequests().anyRequest().authenticated();
        // 配置登录成功后默认页面
        http.formLogin().successHandler(new LoginSuccessHandler());
        // 配置登录失败
        http.formLogin().failureHandler(new LoginFailHandler());
        //登录过期页面
        http.exceptionHandling().authenticationEntryPoint(new LoginExptionHandler());
//        // 访问权限不足页面跳转
        http.exceptionHandling().accessDeniedHandler(new AuthLimitHandler());
        // 默认登录页面
        http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/login");
//        // 登出登出
        //  rest 无状态 无session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.logout().permitAll();
    }


    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };

    }
}
